package com.bsh.repository;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.bsh.mybatis.IRepository.CloudMoneyLogMapper;
import com.bsh.mybatis.model.CloudMoneyLog;
import com.bsh.utils.Pager;
import com.mysql.jdbc.StringUtils;


@Repository
public class DaoCloudMoneyLog {
	@Resource
	SqlSessionTemplate session;
	@Resource
	JdbcTemplate jdbcTemplate;
	@Resource
	NamedParameterJdbcTemplate namedJdbcTemplate;
	
	CloudMoneyLogMapper getMapper(){
		return session.getMapper(CloudMoneyLogMapper.class);
	}
		
	public int deleteByPrimaryKey(Integer id) {
		int res = getMapper().deleteByPrimaryKey(id);
		return res;
	}

	public int insert(CloudMoneyLog record) {
		int res = getMapper().insert(record);
		return record.getId();
	}

	public int insertSelective(CloudMoneyLog record) {
		int res = getMapper().insertSelective(record);
		return record.getId();
	}

	public CloudMoneyLog selectByPrimaryKey(Integer id) {
		CloudMoneyLog row = getMapper().selectByPrimaryKey(id);
		return row;
	}

	public int updateByPrimaryKeySelective(CloudMoneyLog record) {
		int res = getMapper().updateByPrimaryKeySelective(record);
		return res;
	}

	public int updateByPrimaryKey(CloudMoneyLog record) {
		int res = getMapper().updateByPrimaryKey(record);
		return res;
	}


	/**
	 * 分页查询
	 */
	public List<Map<String, Object>> getPage(Pager pager, String where) {
		StringBuilder sb = new StringBuilder();
		MapSqlParameterSource ps = new MapSqlParameterSource();
		sb.append("select m.*,cat.name category_name,u.name user_name,rp.name province_name,rc.name city_name,ra.name area_name from merchant m ");
		sb.append("join user u on u.id=m.userid ");
		sb.append("join merchant_category cat on cat.id=m.category ");
		sb.append("join region rp on rp.id=m.province ");
		sb.append("join region rc on rc.id=m.city ");
		sb.append("join region ra on ra.id=m.area ");

		if (!StringUtils.isNullOrEmpty(where)) {
			sb.append(where);
		}
		Integer count = namedJdbcTemplate.queryForInt("select count(0) from (" + sb.toString() + ")v", ps);

		sb.append(" order by m.id desc limit :start,:size");
		ps.addValue("start", pager.getStart());
		ps.addValue("size", pager.getPageSize());
		List<Map<String, Object>> list = namedJdbcTemplate.queryForList(sb.toString(), ps);

		pager.setRowCount(count);
		return list;
	}

}
